from prg.common.array_queue import ArrayQueue
from prg.common.object_message import MessageBase


class UdpCommand(MessageBase):
    def __init__(self, socket_item):
        super().__init__(name="udp_command")
        self.socket_item = socket_item
        self.command_queue = ArrayQueue()
        self.encryption = None
        self.link = False

    def add(self, cmd):
        self.command_queue.put(cmd)

    def command_run(self, encryption=None):
        self.encryption = encryption
        self.start()

    def send_run(self):
        while self.is_run():
            if not self.command_queue.empty():
                cmd = self.command_queue.read()
                link_inf = (str(self.socket_item.getsockname()), str(self.socket_item.getpeername()))
                try:
                    cmd.send(self.socket_item, encryption=self.encryption)
                except Exception as e:
                    print("send error, socket name: %s, peer name:%s" % link_inf)
                    print("error: %s" % e)
                    break
                else:
                    if not self.link:
                        print("link is ok, socket name: %s, peer name:%s" % link_inf)
                        self.link = True
                    self.command_queue.get()

    def end(self):
        self.command_queue.clear()

    def entry(self):
        self.send_run()
